<?php

class Database
{
    private $user;            //用户名
    private $pwd;            //用户密码
    private $host;            //数据库连接地址
    private $dbName;        //数据库名
    private $port;            //端口
    private $link;            //数据库连接
    private $result;        //结果集
    public static $str;     //静态对象

    //构造函数
    private function __construct($config)
    {
        $this->host = $config['host'];
        $this->user = $config['user'];
        $this->pwd = $config['pwd'];
        $this->dbName = $config['dbName'];
        $this->port = $config['port'];
        $this->link = mysqli_connect($this->host, $this->user, $this->pwd, $this->dbName, $this->port);
        mysqli_query($this->link,"set names 'utf8'");
    }

    //静态创建对象
    public static function createObj($config)
    {
        if (self::$str == null) {
            self::$str = new Database($config);
        }
        return self::$str;
    }

    //执行语句
    public static function exeSql($sql)
    {
        self::$str->result = mysqli_query(self::$str->link, $sql);
        return self::$str->result;
    }

    //返回查询结果
    public static function query($sql)
    {
        self::exeSql($sql);
        if (self::$str->result) {
            $arr = [];
            while ($row = mysqli_fetch_assoc(self::$str->result)) {
                $arr[] = $row;
            }
            return $arr;
        } else {
            return false;
        }
    }

    public static function change($sql)
    {
        self::exeSql($sql);
        $result = mysqli_affected_rows(self::$str->link);
        return $result;
    }

    //析构函数
    public function __destruct()
    {
        @mysqli_free_result($this->result);
        mysqli_close($this->link);
    }
}
$dbconfig=[//配置文件
    'host'=>'localhost',
    'user'=>'bfhosucj',
    'pwd'=>'aOKABkOt',
    'dbName'=>'bfhosucj',
    'port' => 3306
];
Database::createObj($dbconfig);
